﻿namespace Zen.BlackBerry.Web.Controllers
{
	using System;
	using System.Linq;
	using System.Web;
	using System.Web.Mvc;
	using Microsoft.Practices.Unity;
	using Zen.BlackBerry.Push.AppManagement;
	using Zen.BlackBerry.Web.Models;

	/// <summary>
	/// <c>ApplicationController</c> implements a MVC controller for actions
	/// related to push application management.
	/// </summary>
	public class ApplicationController : Controller
	{
		[Dependency]
		public IPushApplicationService ApplicationService
		{
			get;
			set;
		}

		//
		// GET: /Application/

		public ActionResult Index()
		{
			ApplicationModel[] models = ApplicationService
				.FindAll()
				.Select((item) =>
					new ApplicationModel
					{
						Id = item.Id,
						ApplicationId = item.RimApplicationId,
						ApplicationType = item.Type,
						AutoDeleteRequests = item.AutoDeleteRequests,
						BypassSubscriptions = item.BypassSubscriptions,
						CreatedDate = item.CreatedDate,
						DefaultPushTtl = item.DefaultPushLiveTime,
						Description = item.Description,
						EnterpriseNotificationUrl = item.EnterpriseNotifyUrl,
						EnterprisePassword = item.EnterprisePassword,
						ExpiryDate = item.ExpiryDate,
						IsDisabled = item.Status == PushApplicationStatus.Inactive,
						IsLastNotificationEnabled = item.IsLastNotificationEnabled,
						IsReliable = item.IsApplicationReliable,
						IsStoringRequests = item.IsStorePushRequests,
						LastUpdateBy = item.ModifiedBy,
						LastUpdateDate = item.ModifiedDate,
						MaximumDailyPushes = item.MaximumDailyPushes,
						Name = item.Name,
						PublicNotificationUrl = item.PublicNotifyUrl,
						PublicPassword = item.PublicPassword,
						PushPort = item.PushPort,
						ServiceLevel = item.ServiceLevel,
						StartDate = item.StartDate,
						UserName = item.UserName,
						Version = item.Version
					})
				.ToArray();
			return View(models);
		}

		public ActionResult Create()
		{
			DateTime now = DateTime.UtcNow;

			return View(
				new ApplicationModel
				{
					Id = Guid.NewGuid(),
					CreatedDate = now,
					LastUpdateDate = now,
					LastUpdateBy = GetCurrentUser(),
					StartDate = now,
					ExpiryDate = now + TimeSpan.FromDays(120),
					DefaultPushTtl = TimeSpan.FromDays(14),
					ApplicationType = PushApplicationType.PublicPush,
					ServiceLevel = PushApplicationServiceLevel.PushEssentials,
					Version = "1.0.0.0"
				});
		}

		[HttpPost]
		public ActionResult Create(ApplicationModel model)
		{
			try
			{
				if (!ModelState.IsValid)
				{
					return View(model);
				}
				else
				{
					PushApplication app =
						new PushApplication
						{
							Id = model.Id,
							AutoDeleteRequests = model.AutoDeleteRequests,
							BypassSubscriptions = model.BypassSubscriptions,
							DefaultPushLiveTime = model.DefaultPushTtl,
							Description = model.Description,
							EnterpriseNotifyUrl = model.EnterpriseNotificationUrl,
							EnterprisePassword = model.EnterprisePassword,
							ExpiryDate = model.ExpiryDate,
							IsApplicationReliable = model.IsReliable,
							IsLastNotificationEnabled = model.IsLastNotificationEnabled,
							IsStorePushRequests = model.IsStoringRequests,
							MaximumDailyPushes = model.MaximumDailyPushes,
							Name = model.Name,
							PublicNotifyUrl = model.PublicNotificationUrl,
							PublicPassword = model.PublicPassword,
							PushPort = model.PushPort,
							RimApplicationId = model.ApplicationId,
							ServiceLevel = model.ServiceLevel,
							StartDate = model.StartDate,
							Status = model.IsDisabled ? PushApplicationStatus.Inactive : PushApplicationStatus.Active,
							Type = model.ApplicationType,
							UserName = model.UserName,
							ModifiedBy = GetCurrentUser(),
							Version = model.Version,
						};
					ApplicationService.AddPushApplication(app);
					return this.RedirectToAction("Index");
				}
			}
			catch
			{
				return View(model);
			}
		}

		public ActionResult Edit(Guid id)
		{
			PushApplication item = ApplicationService.FindById(id);
			ApplicationModel model =
				new ApplicationModel
				{
					Id = item.Id,
					ApplicationId = item.RimApplicationId,
					ApplicationType = item.Type,
					AutoDeleteRequests = item.AutoDeleteRequests,
					BypassSubscriptions = item.BypassSubscriptions,
					CreatedDate = item.CreatedDate,
					DefaultPushTtl = item.DefaultPushLiveTime,
					Description = item.Description,
					EnterpriseNotificationUrl = item.EnterpriseNotifyUrl,
					EnterprisePassword = item.EnterprisePassword,
					ExpiryDate = item.ExpiryDate,
					IsDisabled = item.Status == PushApplicationStatus.Inactive,
					IsLastNotificationEnabled = item.IsLastNotificationEnabled,
					IsReliable = item.IsApplicationReliable,
					IsStoringRequests = item.IsStorePushRequests,
					LastUpdateBy = item.ModifiedBy,
					LastUpdateDate = item.ModifiedDate,
					MaximumDailyPushes = item.MaximumDailyPushes,
					Name = item.Name,
					PublicNotificationUrl = item.PublicNotifyUrl,
					PublicPassword = item.PublicPassword,
					PushPort = item.PushPort,
					ServiceLevel = item.ServiceLevel,
					StartDate = item.StartDate,
					UserName = item.UserName,
					Version = item.Version
				};
			return View(model);
		}

		[HttpPost]
		public ActionResult Edit(ApplicationModel model)
		{
			try
			{
				if (!ModelState.IsValid)
				{
					return View(model);
				}
				else
				{
					PushApplication app = ApplicationService.FindById(model.Id);
					app.AutoDeleteRequests = model.AutoDeleteRequests;
					app.BypassSubscriptions = model.BypassSubscriptions;
					app.DefaultPushLiveTime = model.DefaultPushTtl;
					app.Description = model.Description;
					app.EnterpriseNotifyUrl = model.EnterpriseNotificationUrl;
					app.EnterprisePassword = model.EnterprisePassword;
					app.ExpiryDate = model.ExpiryDate;
					app.IsApplicationReliable = model.IsReliable;
					app.IsLastNotificationEnabled = model.IsLastNotificationEnabled;
					app.IsStorePushRequests = model.IsStoringRequests;
					app.MaximumDailyPushes = model.MaximumDailyPushes;
					app.ModifiedBy = GetCurrentUser();
					app.Name = model.Name;
					app.PublicNotifyUrl = model.PublicNotificationUrl;
					app.PublicPassword = model.PublicPassword;
					app.PushPort = model.PushPort;
					app.RimApplicationId = model.ApplicationId;
					app.ServiceLevel = model.ServiceLevel;
					app.StartDate = model.StartDate;
					app.Status = model.IsDisabled ? PushApplicationStatus.Inactive : PushApplicationStatus.Active;
					app.Type = model.ApplicationType;
					app.UserName = model.UserName;
					app.Version = model.Version;

					ApplicationService.UpdatePushApplication(app);
					return this.RedirectToAction("Index");
				}
			}
			catch
			{
				return View(model);
			}
		}

		public ActionResult Delete(Guid id)
		{
			PushApplication item = ApplicationService.FindById(id);
			DeleteApplicationModel model =
				new DeleteApplicationModel
				{
					Id = item.Id,
					CreatedDate = item.CreatedDate,
					Description = item.Description,
					Name = item.Name,
					Version = item.Version,
					UnsubscribeBeforeDelete = true
				};
			return View(model);
		}

		[HttpPost]
		public ActionResult Delete(DeleteApplicationModel model)
		{
			try
			{
				if (!ModelState.IsValid)
				{
					return View(model);
				}
				else
				{
					PushApplication app = ApplicationService.FindById(model.Id);
					if (app != null)
					{
						ApplicationService.DeletePushApplication(
							app.RimApplicationId,
							GetCurrentUser(),
							model.UnsubscribeBeforeDelete);
					}
					return this.RedirectToAction("Index");
				}
			}
			catch
			{
				return View(model);
			}
		}

		private string GetCurrentUser()
		{
			string user = "[unknown]";
			if (HttpContext.User != null &&
				HttpContext.User.Identity != null &&
				HttpContext.User.Identity.IsAuthenticated)
			{
				user = HttpContext.User.Identity.Name;
			}
			return user;
		}
	}
}
